<template>
  <view class="content">
    <uni-forms :rules="rules" :model="addressForm" ref="addressFormRef">
      <!-- 表单内容 -->
      <uni-forms-item class="form-item" name="receiver">
        <text class="label">收货人</text>
        <input class="input" placeholder="请填写收货人姓名" v-model="addressForm.receiver" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="contact">
        <text class="label">手机号码</text>
        <input class="input" placeholder="请填写收货人手机号码" v-model="addressForm.contact" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="countyCode">
        <text class="label">所在地区</text>
        <!-- #ifdef MP-WEIXIN -->
        <picker
          class="picker"
          mode="region"
          :value="addressForm.fullLocation"
          @change="onChangeFullLocation"
        >
          <view v-if="addressForm.fullLocation">广东省 广州市 天河区</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
        <!-- #endif -->
        <!-- #ifdef APP-PLUS || H5 -->
        <uni-data-picker
          placeholder="请选择地址"
          popup-title="请选择城市"
          collection="opendb-city-china"
          field="code as value, name as text"
          orderby="value asc"
          :step-searh="true"
          self-field="code"
          parent-field="parent_code"
          @change="onchange"
        >
        </uni-data-picker>
        <!-- #endif -->
      </uni-forms-item>
      <uni-forms-item class="form-item" name="address">
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="addressForm.address" />
      </uni-forms-item>
      <uni-forms-item class="form-item">
        <label class="label">设为默认地址</label>
        <switch
          class="switch"
          color="#ff3304"
          :checked="addressForm.isDefault === 1"
          @change="onChangeDefault"
        />
      </uni-forms-item>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <button class="button" @click="onSubmit">保存并使用</button>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { postAddAddressAPI, getAddressDetailAPI } from '@/api/address'
import { onLoad } from '@dcloudio/uni-app'
// 引入ts类型
import type { addressInfoType } from '@/types/address'
// 获取传递过来的id
const params = defineProps<{
  id?: string
}>()
// 动态设置导航栏标题
uni.setNavigationBarTitle({
  title: params.id ? '修改地址' : '新建地址',
})
// 表单数据
const addressForm = ref<addressInfoType>({
  id: '',
  receiver: '', // 收货人
  contact: '', // 联系方式
  fullLocation: '', // 省市区(前端展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0, // 默认地址，1为是，0为否
})
// 地区发生改变时的回调
// #ifdef MP-WEIXIN
const onChangeFullLocation = (e: any) => {
  addressForm.value.fullLocation = e.detail.value.join(' ')
  // 保存省市区编码
  addressForm.value.provinceCode = e.detail.code[0]
  addressForm.value.cityCode = e.detail.code[1]
  addressForm.value.countyCode = e.detail.code[2]
}
// #endif
// #ifdef APP-PLUS || H5
const onchange = (e: any) => {
    // 保存省市区编码
  addressForm.value.provinceCode = e.detail.value[0].value
  addressForm.value.cityCode = e.detail.value[1].value
  addressForm.value.countyCode = e.detail.value[2].value
  console.log(addressForm.value)
}
// #endif

// 开关发生变化的回调
const onChangeDefault = (e: any) => {
  addressForm.value.isDefault = e.detail.value ? 1 : 0
}
// 表单ref对象
const addressFormRef = ref()
// 表单校验规则
const rules = ref({
  receiver: {
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '请填写收货人姓名',
      },
    ],
  },
  contact: {
    rules: [
      {
        required: true,
        errorMessage: '请填写收货人手机号码',
      },
      {
        validateFunction: (rule: any, value: string, data: any, callback: any) => {
          const regExp =
            /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
          if (!regExp.test(value)) {
            callback('请输入正确的手机号码')
          }
          return true
        },
      },
    ],
  },
  countyCode: {
    rules: [
      {
        required: true,
        errorMessage: '请填写省/市/区(县)',
      },
    ],
  },
  address: {
    rules: [
      {
        required: true,
        errorMessage: '请填写详细地址',
      },
    ],
  },
})
// const pages = getCurrentPages()
// const prevPages = pages[pages.length -2]   // 上一个页面的实例
// prevPages.$vm.$mp.text = '新建地址'
// 保存按钮的回调
const onSubmit = () => {
  addressFormRef.value
    .validate()
    .then(async () => {
      await postAddAddressAPI(addressForm.value)
      // 接口调用成功，提示用户
      uni.showToast({
        title: addressForm.value.id ? '修改成功' : '添加成功',
        icon: 'success',
      })
      setTimeout(() => {
        // 回到上一页
        uni.navigateBack()
      }, 300)
    })
    .catch((err: any) => {
      console.log(err)
    })
}

// 获取地址详情的函数
const getAddressDetail = async (id: string) => {
  const res = await getAddressDetailAPI(id)
  if (res.code === '1') {
    addressForm.value = res.result
  }
}
onLoad(() => {
  if (params.id) {
    getAddressDetail(params.id)
  }
})
</script>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx 40rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    // 调整 uni-forms 样式
    .uni-forms-item__content {
      display: flex;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
    }

    &:last-child {
      border: none;
    }

    .label {
      width: 200rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: -20rpx;
      transform: scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #ff3304;
}
</style>
